package activity.live.fragment;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import com.hichip.callback.ICameraIOSessionCallback;
import com.hichip.callback.ICameraPlayStateCallback;
import com.hichip.campro.R;
import com.hichip.control.HiCamera;
import java.io.File;
import java.util.Timer;
import java.util.TimerTask;
import activity.live.LiveViewActivity;
import base.HiFragment;
import bean.MyCamera;
import butterknife.BindView;
import butterknife.ButterKnife;
import common.HiDataValue;
import utils.HiToast;
import utils.HiTools;

public class FirstTabFragment extends HiFragment implements View.OnClickListener, ICameraIOSessionCallback, ICameraPlayStateCallback {
    private MyCamera mMyCamera;
    @BindView(R.id.iv_listen) public ImageView iv_listen;
    @BindView(R.id.iv_record) public ImageView iv_record;
    @BindView(R.id.iv_snapshot) public ImageView iv_snapshot;
    @BindView(R.id.iv_duijiang) public ImageView iv_duijiang;
    @BindView(R.id.ll_square) LinearLayout ll_square;
    @BindView(R.id.ll_root) RelativeLayout ll_root;


    private LiveViewActivity mAct;
    private boolean mVoiceIsTran = false; // 当前声音是否是传输状态
    private Timer timer;
    private TimerTask timerTask;

    private int mHeight;//下面 fragment 高度


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_live_first_tab, null);
        ButterKnife.bind(this, view);
        initViewAndData();
        setListeners();
        return view;
    }

    private void setListeners() {
        iv_listen.setOnClickListener(this);
        iv_record.setOnClickListener(this);
        iv_snapshot.setOnClickListener(this);
        iv_duijiang.setOnClickListener(this);
    }

    private void initViewAndData() {
        mAct = (LiveViewActivity) getActivity();
        //界面适配
        DisplayMetrics dm=new DisplayMetrics();
        mAct.getWindowManager().getDefaultDisplay().getMetrics(dm);
        int screenW=dm.widthPixels;
        ll_square.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                ll_square.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                mHeight=ll_square.getHeight();
                int min=Math.min(screenW,mHeight);
                Log.i("tedu","--screenW--:"+screenW+"::"+"--mHeight--:"+mHeight+"-min-:"+min);
                RelativeLayout.LayoutParams params= (RelativeLayout.LayoutParams) ll_square.getLayoutParams();
                params.height=min;
                params.width=min;
                int dix10=HiTools.dip2px(getContext(),10);
                int rote=0;
                if(min==screenW){
                    rote=dix10/2;
                }
                if((min+HiTools.dip2px(getContext(),35))>screenW){//为了让正方形稍微小一点
                    rote=dix10;
                    dix10+=dix10;
                }
                Log.i("tedu","--rote--:"+rote+"--dix10--:"+dix10);
                params.setMargins(rote,dix10,rote,dix10);
                params.addRule(RelativeLayout.CENTER_IN_PARENT);
                ll_square.setLayoutParams(params);
            }
        });







    }

    public void initHeight(int height) {
        this.mHeight = height;
    }

    public void setmMyCamera(MyCamera camera) {
        this.mMyCamera = camera;
        mMyCamera.registerIOSessionListener(this);
        mMyCamera.registerPlayStateListener(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mMyCamera != null) {
            mMyCamera.unregisterPlayStateListener(this);
            mMyCamera.unregisterIOSessionListener(this);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_listen:
                if (HiDataValue.ANDROID_VERSION >= 6 && (!HiTools.checkPermission(getActivity(), Manifest.permission.RECORD_AUDIO))) {
                    showAlertDialog();
                    return;
                }
                clickListen();
                break;
            case R.id.iv_record://录像
                if (HiDataValue.ANDROID_VERSION >= 6 && (!HiTools.checkPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE))) {
                    showAlertDialog();
                    return;
                }
                handRecord();
                break;
            case R.id.iv_snapshot://截图
                if (HiDataValue.ANDROID_VERSION >= 6 && (!HiTools.checkPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE))) {
                    showAlertDialog();
                    return;
                }
                handSnapshot();
                break;
            case R.id.iv_duijiang://对讲
                if (HiDataValue.ANDROID_VERSION >= 6 && (!HiTools.checkPermission(getActivity(), Manifest.permission.RECORD_AUDIO))) {
                    showAlertDialog();
                    return;
                }
                handTalking();
                break;

        }

    }

    private void handTalking() {
        if (mAct.mRecordingState == LiveViewActivity.RECORDING_STATUS_ING) {
            mMyCamera.PausePlayAudio();
        } else {
            mMyCamera.stopListening();
            mVoiceIsTran = false;
        }
        if (mAct.isTalking) {
            mMyCamera.stopTalk();
        } else {
            mMyCamera.startTalk();
        }
        if (mAct.isListening) {
            mMyCamera.stopListening();
            mVoiceIsTran = false;
            iv_listen.setSelected(false);
            mAct.iv_landscape_listen.setSelected(false);
            mAct.isListening = !mAct.isListening;
        }
        mAct.isTalking = !mAct.isTalking;
        iv_duijiang.setSelected(mAct.isTalking);
        mAct.iv_landscape_talk.setSelected(mAct.isTalking);
    }


    private void handSnapshot() {
        mAct.clickSnapshot();
    }


    // 点击声音按钮开始监听语音，按住喇叭说话，松开接收
    private void clickListen() {
        if (mAct.mRecordingState == LiveViewActivity.RECORDING_STATUS_ING) {// 正在录像中...
            if (mVoiceIsTran) {
                mMyCamera.PausePlayAudio();
                if(mAct.isListening){
                    mMyCamera.PausePlayAudio();
                }else{
                    mMyCamera.ResumePlayAudio();
                }
            } else {
                mMyCamera.stopRecording();
                mMyCamera.startListening();
                mVoiceIsTran = true;
                TimerRecording();
                mAct.mStartRecoedTime=0;
            }
            if (mAct.isListening) {
                mAct.iv_landscape_listen.setSelected(false);
                iv_listen.setSelected(false);
            } else {
                mAct.iv_landscape_listen.setSelected(true);
                iv_listen.setSelected(true);
            }
        } else {
            if (mAct.isListening) {
                mAct.iv_landscape_listen.setSelected(false);
                iv_listen.setSelected(false);
                mMyCamera.stopListening();
                mVoiceIsTran = false;
            } else {
                mAct.iv_landscape_listen.setSelected(true);
                iv_listen.setSelected(true);
                mMyCamera.startListening();
                mVoiceIsTran = true;
            }
        }
        if (mAct.isTalking) {
            iv_duijiang.setSelected(false);
            mAct.iv_landscape_talk.setSelected(false);
            mMyCamera.stopTalk();
            mAct.isTalking = !mAct.isTalking;
        }
        mAct.isListening = !mAct.isListening;
    }


    private void handRecord() {
        clickRecording();
    }

    // 点击录像按钮，保存录像文件
    private void clickRecording() {
        if (mAct.mRecordingState == LiveViewActivity.RECORDING_STATUS_NONE) {
            mAct.mRecordingState = LiveViewActivity.RECORDING_STATUS_ING;
            TimerRecording();
            iv_record.setSelected(true);
            mAct.iv_landscape_record.setSelected(true);

            mAct.mStartRecoedTime = 0;
            mAct.ll_recording.setVisibility(View.VISIBLE);
            mAct.iv_recording.setVisibility(View.VISIBLE);
            mAct.mRecHandler.sendEmptyMessage(110);
        } else if (mAct.mRecordingState == LiveViewActivity.RECORDING_STATUS_ING) {
            mAct.mRecordingState = LiveViewActivity.RECORDING_STATUS_NONE;
            if (mVoiceIsTran && !iv_listen.isSelected()) {
                mMyCamera.stopListening();
                mVoiceIsTran = false;
            }
            mMyCamera.stopRecording();
            if (timer != null) {
                timer.cancel();
                timer = null;
            }
            if (timerTask != null) {
                timerTask.cancel();
                timerTask = null;
            }
            iv_record.setSelected(false);
            mAct.iv_landscape_record.setSelected(false);

            mAct.ll_recording.setVisibility(View.INVISIBLE);
            mAct.iv_recording.setVisibility(View.INVISIBLE);
            mAct.mRecHandler.removeCallbacksAndMessages(null);
        }
    }

    private void TimerRecording() {
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (timerTask != null) {
            timerTask.cancel();
            timerTask = null;
        }
        final File cameraFolder = new File(HiDataValue.getPathCameraVideoLocalRecord(mMyCamera.getUid(),mAct));
        if (!cameraFolder.exists()) {
            cameraFolder.mkdirs();
        }
        timer = new Timer();
        timerTask = new TimerTask() {
            boolean isFirst = true;

            @Override
            public void run() {
                if (mAct.mRecordingState == LiveViewActivity.RECORDING_STATUS_ING) {
                    mMyCamera.stopRecording();
                }
                mAct.recordFile = cameraFolder.getAbsoluteFile() + "/" + HiTools.getFileNameWithTime(1);
                long available = HiTools.getAvailableSize();
                if (available < 100 && available > 0) {// 设备内存小于100M
                    mHandler.sendEmptyMessage(0X999);
                    return;
                }
                if (isFirst) {
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            mMyCamera.startRecording(mAct.recordFile);
                            isFirst = false;
                        }
                    });
                } else {
                    mHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mMyCamera.startRecording(mAct.recordFile);
                        }
                    }, 1000);
                }
            }
        };
        timer.schedule(timerTask, 0, 10 * 60 * 1000);
    }


    private void showAlertDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setMessage(getString(R.string.tips_no_permission));
        builder.setPositiveButton(getString(R.string.setting), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                HiTools.toSelfSetting(getActivity());
            }
        });
        builder.setNegativeButton(getString(R.string.cancel), null);
        builder.show();
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                // 播放状态
                case HiDataValue.HANDLE_MESSAGE_PLAY_STATE:
                    handMsgPlayState(msg);
                case HiDataValue.HANDLE_MESSAGE_RECEIVE_IOCTRL:
                    break;
                case 0X999:
                    HiToast.showToast(getActivity(), getString(R.string.failed_recording));
                    break;
            }

        }
    };

    private void handMsgPlayState(Message msg) {
        Bundle bundle = msg.getData();
        int command = bundle.getInt("command");
        switch (command) {
            // 本地录像开始
            case ICameraPlayStateCallback.PLAY_STATE_RECORDING_START:
                grabRecordSnapshot();
                break;
            // 本地录像结束
            case ICameraPlayStateCallback.PLAY_STATE_RECORDING_END:
            case ICameraPlayStateCallback.PLAY_STATE_RECORD_ERROR:
                File file = new File(mAct.recordFile);
                if (file.length() <= 1024 && file.isFile() && file.exists()) {
                    file.delete();
                }
                break;
        }
    }

    private void grabRecordSnapshot() {
        Bitmap frame = mMyCamera != null ? mMyCamera.getSnapshot_EXT(1, 640, 352) : null;
        if (frame != null) {
            saveRecordSnapshot(frame);
        }
    }

    private void saveRecordSnapshot(final Bitmap frame) {
        new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(Void... arg0) {
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                    String path = HiDataValue.getPathCameraLocalRecordSnapShot(mMyCamera.getUid(),mAct);
                    File file = new File(path);
                    if (!file.exists()) {
                        file.mkdirs();
                    }
                    if (!TextUtils.isEmpty(mAct.recordFile)) {
                        File f = new File(mAct.recordFile);
                        if (f != null && f.exists()) {
                            HiTools.saveBitmap(frame, file.getAbsolutePath() + "/" + f.getName());
                        }
                    }
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void result) {
            }
        }.execute();

    }


    @Override
    public void receiveSessionState(HiCamera arg0, int arg1) {
        if (mMyCamera != arg0) return;
        Message msg = mHandler.obtainMessage();
        msg.what = HiDataValue.HANDLE_MESSAGE_SESSION_STATE;
        msg.arg1 = arg1;
        msg.obj = arg0;
        mHandler.sendMessage(msg);

    }

    @Override
    public void receiveIOCtrlData(HiCamera arg0, int arg1, byte[] arg2, int arg3) {
        if (arg0 != mMyCamera) return;
        Bundle bundle = new Bundle();
        bundle.putByteArray(HiDataValue.EXTRAS_KEY_DATA, arg2);
        Message msg = mHandler.obtainMessage();
        msg.what = HiDataValue.HANDLE_MESSAGE_RECEIVE_IOCTRL;
        msg.obj = arg0;
        msg.arg1 = arg1;
        msg.arg2 = arg3;
        msg.setData(bundle);
        mHandler.sendMessage(msg);
    }

    @Override
    public void callbackState(HiCamera camera, int arg1, int arg2, int arg3) {
        if (mMyCamera != camera) return;
        Bundle bundle = new Bundle();
        bundle.putInt("command", arg1);
        bundle.putInt("width", arg2);
        bundle.putInt("height", arg3);
        Message msg = mHandler.obtainMessage();
        msg.what = HiDataValue.HANDLE_MESSAGE_PLAY_STATE;
        msg.setData(bundle);
        mHandler.sendMessage(msg);
    }

    @Override
    public void callbackPlayUTC(HiCamera hiCamera, int i) {

    }


}
